/**
 * 3
 *  
 * @Author : Ruoyu Wang
 * @DateTime : 24-9-21 上午10:56
 */

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

struct node {
    string address;
    int data;
    string next;

    node() {}

    node(string address, int data, string next) {
        this->address = address;
        this->data = data;
        this->next = next;
    }
};

int main() {
    string start;
    int n, k;
    cin >> start >> n >> k;
    unordered_map<string, node> map;
    for (int i = 0; i < n; ++i) {
        string idx, next;
        int x;
        cin >> idx >> x >> next;
        map[idx] = {idx, x, next};
    }

    vector<node> list;
    string p = start;
    while (p != "-1") {
        list.push_back(map[p]);
        p = map[p].next;
    }

    if (k != 1) {
        int idx = 0;
        while (idx + k - 1 < n) {
            for (int i = idx, j = idx + k - 1; i < j; ++i, --j) {
                swap(list[i], list[j]);
            }
            idx = idx + k;
        }
    }

    for (int i = 0; i < list.size(); ++i) {
        cout << list[i].address << " " << list[i].data << " ";
        if (i != list.size() - 1) {
            cout << list[i + 1].address;
        } else {
            cout << -1;
        }
        cout << endl;
    }

    return 0;
}